package com.base.self.service.impl;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.base.result.PageUtils;
import com.base.result.ResponseResult;
import com.base.result.ResponseResultUtils;
import com.base.self.common.SelfRuntimeException;
import com.base.self.dto.commodityClassify.*;
import com.base.self.entity.Commodity;
import com.base.self.entity.CommodityClassify;
import com.base.self.mapper.CommodityClassifyMapper;
import com.base.self.mapper.CommodityMapper;
import com.base.self.service.ICommodityClassifyService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 商品分类
 *
 * @author XiFYuW
 * @since 2020-11-13
 */
@Service
public class CommodityClassifyServiceImpl extends ServiceImpl<CommodityClassifyMapper, CommodityClassify> implements ICommodityClassifyService {
    private final CommodityClassifyMapper commodityClassifyMapper;

    private final CommodityMapper commodityMapper;

    public CommodityClassifyServiceImpl(CommodityClassifyMapper commodityClassifyMapper,
                                        CommodityMapper commodityMapper) {
        this.commodityClassifyMapper = commodityClassifyMapper;
        this.commodityMapper = commodityMapper;
    }

    @Override
    @Transactional(readOnly = true)
    public ResponseResult commodityClassifyWebList(CommodityClassifyWebListDTO commodityClassifyWebListDTO) {
        String classifyName = commodityClassifyWebListDTO.getClassifyName();
        final Map<String, Object> data = PageUtils.getDateMapBack(() -> page(PageUtils.getPage(
                new Page<>(), commodityClassifyWebListDTO.getOffset(), commodityClassifyWebListDTO.getLimit()),
                new LambdaQueryWrapper<CommodityClassify>()
                        .likeRight(!StringUtils.isEmpty(classifyName), CommodityClassify::getClassifyName, classifyName)
                        .eq(CommodityClassify::getIsDel, 0)
                        .orderByDesc(CommodityClassify::getClassifySort)
                        .orderByDesc(CommodityClassify::getCreateTime))
                ,
                page -> {
                    List<CommodityClassify> data1 = page.getRecords();
                    return data1.stream().peek(x ->
                            Optional.ofNullable(
                                    commodityClassifyMapper.selectOne(
                                            new LambdaQueryWrapper<CommodityClassify>()
                                                    .eq(CommodityClassify::getId, x.getClassifyPid())
                                                    .eq(CommodityClassify::getIsDel, 0)
                                    )
                            ).ifPresent(c -> x.setClassifyPidName(c.getClassifyName()))
                    ).collect(Collectors.toList());
                });
        return ResponseResultUtils.getResponseResultS("查询成功", data);
    }

    @Override
    @Transactional(readOnly = true)
    public ResponseResult getClassifyPidSelectData(ClassifyPidSelectDataDTO classifyPidSelectDataDTO) {
        Map<String, Object> columnMap = new HashMap<>();
        columnMap.put("is_del", 0);
        columnMap.put("classify_pid", classifyPidSelectDataDTO.getClassifyPid());
        List<CommodityClassify> data = commodityClassifyMapper.selectByMap(columnMap);
        return ResponseResultUtils.getResponseResultS("查询成功", data);
    }

    @Override
    @Transactional
    public ResponseResult commodityClassifyAdd(CommodityClassifyAddDTO commodityClassifyAddDTO) {
        Optional.ofNullable(commodityClassifyAddDTO.getClassifyPid()).ifPresent(x -> {
            CommodityClassify commodityClassify = commodityClassifyMapper.selectOne(
                    new QueryWrapper<CommodityClassify>()
                            .eq("is_del", 0)
                            .eq("id", commodityClassifyAddDTO.getClassifyPid())
            );
            Optional.ofNullable(commodityClassify).orElseThrow(() -> new SelfRuntimeException(ResponseResultUtils.getResponseResultF("所选父分类错误，请刷新重试！")));
        });

        final CommodityClassify commodityClassify = CommodityClassify
                .builder()
                .classifyName(commodityClassifyAddDTO.getClassifyName())
                .classifyPid(Optional.ofNullable(commodityClassifyAddDTO.getClassifyPid()).orElse(0))
                .createTime(DateUtil.date())
                .classifyPic(commodityClassifyAddDTO.getClassifyPic())
                .classifySort(commodityClassifyAddDTO.getClassifySort())
                .build();
        save(commodityClassify);
        return ResponseResultUtils.getResponseResultS("添加成功");
    }

    @Override
    @Transactional
    public ResponseResult commodityClassifyUpdate(CommodityClassifyUpdateDTO commodityClassifyUpdateDTO) {
        if (commodityClassifyUpdateDTO.getClassifyPid() != 0) {
            Optional.ofNullable(commodityClassifyUpdateDTO.getClassifyPid()).ifPresent(x -> {
                CommodityClassify commodityClassify = commodityClassifyMapper.selectOne(
                        new QueryWrapper<CommodityClassify>()
                                .eq("is_del", 0)
                                .eq("id", commodityClassifyUpdateDTO.getClassifyPid())
                );
                Optional.ofNullable(commodityClassify).orElseThrow(() -> new SelfRuntimeException(ResponseResultUtils.getResponseResultF("所选父分类错误，请刷新重试！")));
            });
        }

        final CommodityClassify commodityClassify = CommodityClassify
                .builder()
                .id(commodityClassifyUpdateDTO.getId())
                .classifyName(commodityClassifyUpdateDTO.getClassifyName())
                .classifyPid(Optional.ofNullable(commodityClassifyUpdateDTO.getClassifyPid()).orElse(0))
                .updateTime(DateUtil.date())
                .classifyPic(commodityClassifyUpdateDTO.getClassifyPic())
                .classifySort(commodityClassifyUpdateDTO.getClassifySort())
                .build();
        updateById(commodityClassify);

        return ResponseResultUtils.getResponseResultS("修改成功");
    }

    @Override
    @Transactional
    public ResponseResult commodityClassifyDelete(CommodityClassifyDeleteDTO commodityClassifyDeleteDTO) {
        Integer count = commodityClassifyMapper.selectCount(new QueryWrapper<CommodityClassify>()
                .eq("is_del", 0)
                .eq("classify_pid", commodityClassifyDeleteDTO.getId())
        );
        if (count > 0) {
            return ResponseResultUtils.getResponseResultF("该分类有子分类，无法删除。");
        }
        Integer commodityClassifyLevel1Count = commodityMapper.selectCount(new LambdaQueryWrapper<Commodity>()
                .eq(Commodity::getCommodityClassifyLevel1, commodityClassifyDeleteDTO.getId())
                .eq(Commodity::getIsDel, 0)
        );
        Integer commodityClassifyLevel2Count = commodityMapper.selectCount(new LambdaQueryWrapper<Commodity>()
                .eq(Commodity::getCommodityClassifyLevel2, commodityClassifyDeleteDTO.getId())
                .eq(Commodity::getIsDel, 0)
        );
        if (commodityClassifyLevel1Count > 0 || commodityClassifyLevel2Count > 0) {
            return ResponseResultUtils.getResponseResultF("该分类有商品，无法删除。");
        }
        final CommodityClassify commodityClassify = CommodityClassify
                .builder()
                .id(commodityClassifyDeleteDTO.getId())
                .isDel(1)
                .updateTime(DateUtil.date())
                .build();
        updateById(commodityClassify);

        return ResponseResultUtils.getResponseResultS("删除成功");
    }
}
